package com.itheima.system.controller;

import com.github.pagehelper.Page;
import com.itheima.aom.pojo.AomUser;
import com.itheima.entity.PageResult;
import com.itheima.system.service.UserService;
import com.itheima.entity.Result;
import com.itheima.entity.StatusCode;
import com.itheima.system.util.CookieUtil;
import com.itheima.system.util.JwtUtil;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${auth.clientId}")
    private String clientId;

    @Value("${auth.clientSecret}")
    private String clientSecret;

    @Value("${auth.cookieDomain}")
    private String cookieDomain;

    @Value("${auth.cookieMaxAge}")
    private int cookieMaxAge;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 用户登录
     * @param user
     * @return
     */
    @PostMapping("/login")
    public Result login( AomUser user,HttpServletResponse response,HttpSession httpsession) {
        try {
            AomUser loginUser = userService.findUserNameAndPassWord(user);
            if (loginUser!=null){
                httpsession.setAttribute("user",loginUser);
                Map<String,String> info=new HashMap();
                info.put("username",user.getUsername());
                String id= UUID.randomUUID().toString();//设置唯一编号
                String subject = user.getUsername();//主题
                String token = JwtUtil.createJWT(id, subject, null);
                info.put("token",token);
                String jti = info.get("username");
                //存储jti到cookie中
                this.saveJtiToCookie(jti,response);
                redisTemplate.boundValueOps("token"+jti).set(token);
                return new Result(true, StatusCode.OK, "登录成功",info);
            }
            //是否是第一次登录
            if ("0".equals(loginUser.getFirstlogin())) {
                userService.updatePassword(user);
                return new Result(true, StatusCode.OK, "用户修改成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.LOGINERROR, "登录失败,用户名或者密码错误");
    }

    /**
     * 用户退出功能
     * @param request
     * @return
     */
    @GetMapping("/loginOut")
    public Result loginOut(HttpServletRequest request,HttpServletResponse response){
        try {
            //首先用Enumeration的对象来得到所有的session中的信息
            Enumeration<String> em = request.getSession().getAttributeNames();
            //使用循环遍历，执行 removeAttribute（）的session删除操作
            while(em.hasMoreElements()){
                request.getSession().removeAttribute(em.nextElement().toString());
            }
            Cookie[] cookies = request.getCookies();
            for (Cookie c : cookies) {
                if (c.getName().equals("uid")){
                    c.setPath("/");
                    c.setMaxAge(0);
                    response.addCookie(c);
                    break;
                }
            }

//            redisTemplate.delete("token");

            return new Result(true,StatusCode.OK,"用户退出成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.LOGINERROR,"用户退出失败");
    }

    /**
     * 用户添加
     * @param user
     * @return
     */
    @PostMapping("/add")
    public Result addUser(@RequestBody AomUser user,HttpServletRequest request){
        try {
            //从session域中根据储存的"user"取出登录的loginUser用户
           AomUser loginUser = (AomUser) request.getSession().getAttribute("user");
//            //根据用户获取id
//            Long id = loginUser.getId();
//            //给前台传来的User用户中加一个Parentid
//            user.setParentid(id);
//            //因为是从session中取出来的用户信息,直接用这个LoginUser对象,把他的信息重新设置一下,就成了一个新的用户
//            //把loginUser对象的id变成空,让他主键自增长
//            loginUser.setId(null);
//            //user是前台传来的用户
//            String username = user.getUsername();
//            String password = user.getPassword();
//            loginUser.setUsername(username);
//            loginUser.setPassword(password);
            //这样LoginUser就变成了一个新的User了

            userService.addUser(user,loginUser);
            return new Result(true,StatusCode.OK,"添加成功用户成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, StatusCode.ERROR, "添加用户失败");

    }

    /**
     * 用户修改密码
     * @param user
     * @return
     */
    @PutMapping("/updatePs")
    public Result updatePs(@RequestBody AomUser user){
        try {
            userService.updatePassword(user);
            return new Result(true, StatusCode.OK, "用户修改密码成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(false,StatusCode.ERROR,"用户修改密码失败");
    }
    @PutMapping("/updateUser")
    public Result updateUser(@RequestBody AomUser user){
        try {
            userService.updateUser(user);
            return new Result(true, StatusCode.OK, "用户修改成功");
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new Result(false,StatusCode.ERROR,"用户修改失败");
    }
    /**
     * 查询所有用户
     * @param user
     * @return
     */
    @GetMapping("/findAll")
    public Result findAll(AomUser user){
        try {
            List<AomUser> userList = userService.findAllUser(user);
            return new Result(true,StatusCode.OK,"用户查询成功",userList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.ERROR,"用户查询失败");
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    @GetMapping("/findById/{id}")
    public Result findUserById(@PathVariable("id")Integer id){
        try {
            AomUser user = userService.findById(id);
            return new Result(true,StatusCode.OK,"用户查询成功",user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.ERROR,"用户查询失败");
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result deleteUser(@PathVariable("id")Integer id){
        try {
            userService.deleteById(id);
            return new Result(true,StatusCode.OK,"用户删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.ERROR,"用户删除失败");
    }

    /**
     * 分页搜索查询
     * @param page
     * @param size
     * @param username
     * @return
     */
    @GetMapping("/userPage/{page}/{size}")
    public Result userPage(@PathVariable  int page, @PathVariable  int size,String username){
        try {
            Page<AomUser> pagelist = userService.findPage(page, size, username);
            PageResult pageResult = new PageResult(pagelist.getTotal(), pagelist.getResult());
            return new Result(true,StatusCode.OK,"用户查询成功",pageResult);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.OK,"用户查询失败");
    }

    private void saveJtiToCookie(String jti, HttpServletResponse response) {
        /*
         cookieMaxAge: -1  #浏览器关闭时cookie失效 cookie生命周期 以秒为单位
            * @param name     cookie名字  "uid"
            * @param value    cookie值     jti
            * @param maxAge   cookie生命周期 以秒为单位
         */
        CookieUtil.addCookie(response,cookieDomain,"/","uid",jti,cookieMaxAge,false);
    }
}
